//
//  YLCSendQuestionViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/3/17.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCSendQuestionViewController.h"
#import "HXPhotoView.h"
#import "HXPhotoTools.h"
@interface YLCSendQuestionViewController ()<UITextFieldDelegate,HXPhotoViewDelegate>
@property (strong, nonatomic) HXPhotoManager *manager;
@end

@implementation YLCSendQuestionViewController
{
    UITextField *titleField;
    UIImageView *verLineView;
    UITextView *questionView;
    UILabel *maxLabel;
    HXPhotoView *photoView;
    NSArray *photoList;
}
- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
    }
    return _manager;
}
- (UIBarButtonItem *)rightBarButtonItem{
    
    return [YLCFactory createTitleBarButtonItemWithTitle:@"提交" titleColor:RGB(255, 255, 255) selector:@selector(sendMessage) target:self];
}
- (void)sendMessage{
    
    if (JK_IS_STR_NIL(titleField.text)) {
        [SVProgressHUD showErrorWithStatus:@"请输入标题"];
        return;
    }
//    if (<#condition#>) {
//        <#statements#>
//    }
    
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    NSMutableArray *photoBase = [NSMutableArray arrayWithCapacity:0];
    
    for (UIImage *photo in photoList) {
        UIImage *newPhoto = [photo ccc_resizedImage:CGSizeMake(photo.size.width/3, photo.size.height/3) interpolationQuality:kCGInterpolationHigh];
        NSString *photoString = @"";
        if (newPhoto) {
             photoString = [newPhoto base64String];
        }else{
            
            photoString = [photo base64String];
            
        }
        

        [photoBase addObject:[NSString stringWithFormat:@"data:image/jpeg;base64,%@",photoString]];
        
    }
    if (JK_IS_STR_NIL(_caseId)) {
        _caseId = @"";
    }
    [YLCNetWorking loadNetServiceWithParam:@{@"token":model.token,@"userId":model.user_id,@"title":titleField.text,@"content":questionView.text,@"Imgdata":photoBase.copy,@"caseId":_caseId} method:@"POST" urlPath:@"app/case/doSave" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        [SVProgressHUD showSuccessWithStatus:@"发布成功！"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
//    [YLCNetWorking uploadImageWithParam:@{@"token":model.token,@"userId":model.user_id,@"title":titleField.text,@"content":questionView.text} imageList:photoList fileName:@"Imgdata" method:@"POST" urlPath:@"app/case/doSave" delegate:self response:^(id responseObject, NSError *error) {
//
//    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createCustomView];
    
    self.view.backgroundColor = [UIColor whiteColor];
}
- (void)createCustomView{
    titleField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frameWidth, 40)];
    
    titleField.placeholder = @"标题（最多30个字）";
    
    titleField.font = [UIFont systemFontOfSize:14];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
    
    titleField.leftView = leftView;
    
    titleField.leftViewMode = UITextFieldViewModeAlways;
    
    titleField.delegate = self;
    
//    RACSignal *titleSignal = [titleField.rac_textSignal bind:^RACStreamBindBlock{
//        return ^RACStream *(id value, BOOL *stop){
//            shouldShowTool = NO;
//            [self dissMiss];
            
//            return [RACReturnSignal return:value];
//        };
//    }];
    
//    [titleSignal subscribeNext:^(id x) {
//        NSString *text = x;
//    }];
    
    [self.view addSubview:titleField];
    
    [titleField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    verLineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, titleField.frameMaxY, self.view.frameWidth, 0.5)];
    
    verLineView.backgroundColor = YLC_GRAY_COLOR;
    
    [self.view addSubview:verLineView];
    
    questionView = [[UITextView alloc] initWithFrame:CGRectMake(10, verLineView.frameMaxY+5, self.view.frameWidth-20, 100)];
    
    NSString *questionPlaceholder = @"问题描述（选填）\n详细的问题描述有助于获得更为快速准确的回答";
    questionView.placeholder = questionPlaceholder;
    
    questionView.placeholderAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithRed:198.0f/255.0f green:205.0f/255.0f blue:206.0f/255.0f alpha:1]};
    
//    questionView.maxInputLength = 400;
    
    [questionView.rac_textSignal subscribeNext:^(id x) {
        NSString *text = x;
//        maxLabel.text = [NSString stringWithFormat:@"%ld/400",text.length];
    }];
    
    [self.view addSubview:questionView];

    maxLabel = [YLCFactory createLabelWithFont:14 color:RGB(219, 163, 106)];
    
//    maxLabel.text = @"0/400";
    
    maxLabel.frame = CGRectMake(self.view.frameWidth-120, questionView.frameMaxY+10, 100, 30);
    
    [self.view addSubview:maxLabel];
    
    photoView = [HXPhotoView photoManager:self.manager];

    photoView.outerCamera = YES;

    photoView.delegate = self;
    
    photoView.backgroundColor = [UIColor whiteColor];
    
    photoView.frame = CGRectMake(10, maxLabel.frameY+20, self.view.frameWidth-20, 100);
    
    [self.view addSubview:photoView];
    
}
-(void)textFieldDidChange:(UITextField *)textField{
    CGFloat maxLength = 30;
    NSString *toBeString = textField.text;
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position || !selectedRange)
    {
        if (toBeString.length > maxLength)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            }else{
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}
// 当view更新高度时调用
- (void)photoView:(HXPhotoView *)photoView updateFrame:(CGRect)frame{
    NSLog(@"%f",frame.size.height);
}
- (void)photoView:(HXPhotoView *)photoView changeComplete:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photos videos:(NSArray<HXPhotoModel *> *)videos original:(BOOL)isOriginal{
    NSMutableArray *photoContainer = [NSMutableArray arrayWithCapacity:0];
    photoList = [NSArray array];
    for (HXPhotoModel *model in photos) {
        [HXPhotoTools getHighQualityFormatPhoto:model.asset size:model.imageSize succeed:^(UIImage *image) {
            [photoContainer addObject:image];
            photoList = photoContainer.copy;
        } failed:^{
            [photoContainer addObject:model.thumbPhoto];//相机图片
            photoList = photoContainer.copy;
        }];
    }
}
- (NSString *)title{
    return @"发布问答";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
